﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CVsharp.DWZMvc.Models;
using CVsharp.MVClib.Authorize;
using CVsharp.MVClib.Log;
using CVsharp.Jquery.DWZ;

namespace CVsharp.DWZMvc.Controllers
{
    public class AccountController : BaseController
    {
          
        //
        // GET: /Account/LogOn
        [Description("登录页面")]
        [IsAllPermissionAttribute]
        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn
        [HttpPost]
        [Description("登录按钮事件")]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        //TODO:等待反正注入
                        CVsharp.Models.DAL.Infrastructure.SysLog log = new CVsharp.Models.DAL.Infrastructure.SysLog();
                        log.Write(model.UserName, CVsharp.Models.DAL.Infrastructure.SysLogType.Login, "登录系统");
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/LogOff
        [Description("退出功能")]
        [Log(LogContent = "用户登出")]
        public ActionResult LogOff()
        {
            //用于记录登出用户名
            ViewBag.loguser = Session["Username"];
            //撤销MyLogOn内所设定的Session
            Session.Remove("Username");
            Session.Remove("LoginTime");

            FormsAuthentication.SignOut();
            //TODO:等待反正注入
            CVsharp.Models.DAL.Infrastructure.SysLog log = new CVsharp.Models.DAL.Infrastructure.SysLog();
            log.Write(User.Identity.Name, CVsharp.Models.DAL.Infrastructure.SysLogType.LogOff, "用户注销");
            return RedirectToAction("Index", "Home");
        }

        [Description("退出跳转功能")]
        [IsAllPermission]
        public ActionResult Out()
        {
            return View();
        }
        //
        // GET: /Account/Register
        [IsViewPage]
        [Description("用户注册")]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [Description("用户注册按钮")]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        [IsViewPage]
        [Authorize]
        [Description("修改密码")]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword
        [Authorize]
        [HttpPost]
        [Description("修改密码按钮事件")]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess
        [Description("修改密码成功页面")]
        [IsViewPage]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        [Description("设置权限页面")]
        [IsViewPage]
        public ActionResult SetPermission()
        {

            return View();
        }

        [Description("用户树页面")]
        [IsViewPage]
        public ActionResult SetUser()
        {
            return View();
        }

        [Description("权限树页面")]
        [IsViewPage]
        public ActionResult PermissionTree()
        {
            //TODO 转换为Unity
            ActionPermissionService aps = new ActionPermissionService();
            ViewData["aps"] = aps.GetAllActionByAssembly("CVsharp.DWZMvc");
            return View();
        }

        [Description("角色添加用户")]
        [IsViewPage]
        [HttpPost]
        public JsonResult UserJoinRole(string users,string Role)
        {
            string[] usernames = users.Split(',');
            Roles.AddUsersToRole(usernames, Role);
            return Json(CVsharp.Jquery.DWZ.JosnMsg.ResultOK("添加成功！"));
        }

        [Description("获取角色树")]
        public ActionResult RolesTree()
        {
            return View();
        }

        [Description("添角色加页面")]
        [IsViewPage]
        public ActionResult AddRole()
        {
            return View();
        }

        [Description("添角色加功能")]
        [HttpPost]
        public JsonResult AddRole(String RoleName)
        {
            if (Roles.RoleExists(RoleName))
            {
                return Json(JosnMsg.ResultFail("已经存在，请不要反复添加！"));
            }
            else
            {
                Roles.CreateRole(RoleName);
                return Json(JosnMsg.ResultOK("添加成功！"));
            }
        }

        [Description("删角色加功能")]
        [HttpPost]
        public JsonResult DelRole(String RoleName)
        {
            if(RoleName.Equals("admin"))
                return Json(JosnMsg.ResultFail("不能删除管理员角色！"));
            if (Roles.RoleExists(RoleName))
            {
                Roles.DeleteRole(RoleName);
                return Json(JosnMsg.ResultOK("删除成功！"));
                
            }
            else
            {
                return Json(JosnMsg.ResultFail("不存在该角色！"));
            }
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入不同的用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入不同的电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
